package com.nd.fastdp.utils;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;

public class RqcodeUtil {

    public static void create(String name, String url, HttpServletResponse response) throws IOException {

        String rqCodeName = (StringUtils.isNotEmpty(name) ? name : System.currentTimeMillis()) + "." + ImgUtil.IMAGE_TYPE_PNG;

        File qrcodeFile = create(name + "_" + System.currentTimeMillis(), 300, 300, url);

        if (qrcodeFile != null && qrcodeFile.exists()) {
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(rqCodeName, "UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(qrcodeFile);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null)  bis.close();
                if (fis != null) fis.close();
            }
        }else{
            response.setContentType("text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");

            response.getWriter().write("资源不存在");
        }
    }

    public static File create(String name, Integer width, Integer height, String url) throws IOException{

        return create(name, width, height, 4, 1, url);

    }

    public static File create(String name, Integer width, Integer height, Integer ratio, Integer margin, String url) throws IOException{

        File qrcodeFile = File.createTempFile(name, "." + ImgUtil.IMAGE_TYPE_PNG);
        qrcodeFile.deleteOnExit();

        InputStream logoImgStream = new ClassPathResource("static/img/rqcode_logo.png").getInputStream();
        BufferedImage logo = ImageIO.read(logoImgStream);

        QrConfig config = new QrConfig(width, height);
        config.setImg(logo);
        config.setRatio(ratio);
        // 设置边距，既二维码和背景之间的边距
        config.setMargin(margin);
        config.setErrorCorrection(ErrorCorrectionLevel.Q);
        QrCodeUtil.generate(url, config, qrcodeFile);

        return qrcodeFile;
    }
}
